package com.sherllinhe.business.controller;

import cn.hutool.core.util.ObjUtil;
import com.sherllinhe.business.req.ConfirmOrderDoReq;
import com.sherllinhe.business.req.ConfirmOrderQueryReq;
import com.sherllinhe.business.resp.ConfirmOrderQueryResp;
import com.sherllinhe.business.service.BeforeConfirmOrderService;
import com.sherllinhe.business.service.ConfirmOrderService;
import com.sherllinhe.common.context.LoginMemberContext;
import com.sherllinhe.common.resp.CommonResp;
import com.sherllinhe.common.resp.PageResp;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.stringtemplate.v4.ST;

/**
 * 功能：
 * 作者：Sherllin He
 * 日期：
 */
@Slf4j
@RequestMapping("/confirm-order")
@RestController
public class ConfirmOrderController {
    @Autowired
    private BeforeConfirmOrderService beforeConfirmOrderService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ConfirmOrderService confirmOrderService;
    @Value("${spring.profiles.active}")
    private String env;

    @PostMapping("/do")
    public CommonResp<Object> register(@Valid @RequestBody ConfirmOrderDoReq req) throws InterruptedException {
        if (!env.equals("dev")){
            //图形验证码校验
            String imageCode = req.getImageCode();
            String imageCodeToken = req.getImageCodeToken();
            String imageCodeRedis = redisTemplate.opsForValue().get(imageCodeToken);
            if (ObjUtil.isEmpty(imageCodeRedis)){
                return new CommonResp<>(false, "验证码已过期", null);
            }
            if(!imageCodeRedis.equalsIgnoreCase(imageCode)){
                return new CommonResp<>(false, "验证码错误", null);
            }else{
                redisTemplate.delete(imageCodeToken);
            }
        }

        req.setMemberId(LoginMemberContext.getId());
        Long id = beforeConfirmOrderService.beforeConfirmOrder(req);
        return new CommonResp<>(String.valueOf(id));
    }

    @GetMapping("/query-list")
    public CommonResp<PageResp<ConfirmOrderQueryResp>> register(@Valid ConfirmOrderQueryReq req){
        PageResp<ConfirmOrderQueryResp> list = confirmOrderService.queryList(req);
        return new CommonResp<>(list);
    }

    @DeleteMapping("/delete/{id}")
    public CommonResp<Object> delete(@PathVariable Long id){
        confirmOrderService.delete(id);
        return new CommonResp<>();
    }
    @GetMapping("/query-line-count/{confirmOrderId}")
    public CommonResp<Integer> queryLineCount(@PathVariable Long confirmOrderId){
        log.info("查询订单线路数");
        return new CommonResp<>(confirmOrderService.queryLineCount(confirmOrderId));
    }
}
